<commit_before>/** \copyright
 * Copyright (c) 2016, Balazs Racz
 * 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.
 *
 * 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.
 *
 * \file CC32xxEEPROMEmulation.cxx
 * This file implements EEPROM emulation on the CC32xx SPI-flash filesystem.
 *
 * @author Balazs Racz
 * @date 30 December 2016
 */

#include "freertos_drivers/ti/CC32xxEEPROMEmulation.hxx"
#include "freertos_drivers/ti/CC32xxHelper.hxx"
#include "fs.h"

const uint8_t CC32xxEEPROMEmulation::SECTOR_COUNT = 8;

extern "C" {
void eeprom_updated_notification();
}

CC32xxEEPROMEmulation::CC32xxEEPROMEmulation(
    const char *name, size_t file_size_bytes)
    : EEPROM(name, file_size_bytes)
{
    data_ = (uint8_t *)malloc(file_size_bytes);
    HASSERT(data_);
    memset(data_, 0xff, file_size_bytes);
}

void CC32xxEEPROMEmulation::mount()
{
    bool have_rot = false;
    // First we need to find what was the last written segment.
    for (unsigned sector = 0; sector < SECTOR_COUNT; ++sector)
    {
        int handle = open_file(sector, FS_MODE_OPEN_READ, true);
        if (handle < 0)
        {
            continue;
        }
        unsigned b = 0xaa55aaaa;
        SlCheckResult(sl_FsRead(handle, 0, (uint8_t *)&b, 4), 4);
        sl_FsClose(handle, nullptr, nullptr, 0);
        if (b >= fileVersion_)
        {
            readSector_ = sector;
            have_rot = true;
        }
    }

    if (have_rot)
    {
        int handle = open_file(readSector_, FS_MODE_OPEN_READ);
        int ret = sl_FsRead(handle, 4, data_, file_size());
        if (ret < 0)
        {
            SlCheckResult(ret);
        }
    }
}

CC32xxEEPROMEmulation::~CC32xxEEPROMEmulation()
{
    flush();
    free(data_);
}

void CC32xxEEPROMEmulation::flush_buffers()
{
    if (!isDirty_)
        return;
    ++fileVersion_;
    ++readSector_;
    if (readSector_ >= SECTOR_COUNT)
        readSector_ = 0;
    int handle = open_file(readSector_, FS_MODE_OPEN_WRITE, true);
    if (handle < 0)
    {
        handle =
            open_file(readSector_, FS_MODE_OPEN_CREATE(file_size() + 4, 0));
    }
    SlCheckResult(sl_FsWrite(handle, 0, (uint8_t *)&fileVersion_, 4), 4);
    SlCheckResult(sl_FsWrite(handle, 4, data_, file_size()), file_size());
    SlCheckResult(sl_FsClose(handle, nullptr, nullptr, 0));
    isDirty_ = 0;
}

int CC32xxEEPROMEmulation::open_file(
    unsigned sector, uint32_t open_mode, bool ignore_error)
{
    string filename(name);
    filename.push_back('.');
    filename.push_back('0' + sector);
    int32_t handle = -1;
    int ret = sl_FsOpen((uint8_t *)filename.c_str(), open_mode, NULL, &handle);
    if (!ignore_error)
    {
        SlCheckResult(ret);
        HASSERT(handle >= 0);
    }
    return handle;
}

void CC32xxEEPROMEmulation::write(
    unsigned int index, const void *buf, size_t len)
{
    // Boundary checks are performed by the EEPROM class.
    if (isDirty_ || (memcmp(data_ + index, buf, len) != 0))
    {
        isDirty_ = 1;
        memcpy(data_ + index, buf, len);
        eeprom_updated_notification();
    }
}

void CC32xxEEPROMEmulation::read(unsigned int index, void *buf, size_t len)
{
    // Boundary checks are performed by the EEPROM class.
    memcpy(buf, data_ + index, len);
}
<commit_msg>Fixes a silly bug in the CC32xx eeprom emulation.<commit_after>/** \copyright
 * Copyright (c) 2016, Balazs Racz
 * 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.
 *
 * 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.
 *
 * \file CC32xxEEPROMEmulation.cxx
 * This file implements EEPROM emulation on the CC32xx SPI-flash filesystem.
 *
 * @author Balazs Racz
 * @date 30 December 2016
 */

//#define LOGLEVEL VERBOSE

#include "utils/logging.h"

#include "freertos_drivers/ti/CC32xxEEPROMEmulation.hxx"
#include "freertos_drivers/ti/CC32xxHelper.hxx"
#include "fs.h"

const uint8_t CC32xxEEPROMEmulation::SECTOR_COUNT = 8;

extern "C" {
void eeprom_updated_notification();
}

CC32xxEEPROMEmulation::CC32xxEEPROMEmulation(
    const char *name, size_t file_size_bytes)
    : EEPROM(name, file_size_bytes)
{
    data_ = (uint8_t *)malloc(file_size_bytes);
    HASSERT(data_);
    memset(data_, 0xff, file_size_bytes);
}

void CC32xxEEPROMEmulation::mount()
{
    bool have_rot = false;
    // First we need to find what was the last written segment.
    for (unsigned sector = 0; sector < SECTOR_COUNT; ++sector)
    {
        int handle = open_file(sector, FS_MODE_OPEN_READ, true);
        if (handle < 0)
        {
            LOG(VERBOSE, "EEPROM: sector %u: could not open.", sector);
            continue;
        }
        unsigned b = 0xaa55aaaa;
        SlCheckResult(sl_FsRead(handle, 0, (uint8_t *)&b, 4), 4);
        sl_FsClose(handle, nullptr, nullptr, 0);
        LOG(VERBOSE, "EEPROM: sector %u: version %u.", sector, b);
        if (b >= fileVersion_)
        {
            readSector_ = sector;
            fileVersion_ = b;
            have_rot = true;
        }
    }

    if (have_rot)
    {
        LOG(VERBOSE, "EEPROM: read sector %u:", readSector_);
        int handle = open_file(readSector_, FS_MODE_OPEN_READ);
        int ret = sl_FsRead(handle, 4, data_, file_size());
        if (ret < 0)
        {
            SlCheckResult(ret);
        }
    } else {
        LOG(VERBOSE, "EEPROM: no read sector");
    }
}

CC32xxEEPROMEmulation::~CC32xxEEPROMEmulation()
{
    flush();
    free(data_);
}

void CC32xxEEPROMEmulation::flush_buffers()
{
    if (!isDirty_)
        return;
    ++fileVersion_;
    ++readSector_;
    if (readSector_ >= SECTOR_COUNT)
        readSector_ = 0;
    LOG(VERBOSE, "EEPROM: write sector %u version %u", readSector_, fileVersion_);
    int handle = open_file(readSector_, FS_MODE_OPEN_WRITE, true);
    if (handle < 0)
    {
        handle =
            open_file(readSector_, FS_MODE_OPEN_CREATE(file_size() + 4, 0));
    }
    SlCheckResult(sl_FsWrite(handle, 0, (uint8_t *)&fileVersion_, 4), 4);
    SlCheckResult(sl_FsWrite(handle, 4, data_, file_size()), file_size());
    SlCheckResult(sl_FsClose(handle, nullptr, nullptr, 0));
    isDirty_ = 0;
}

int CC32xxEEPROMEmulation::open_file(
    unsigned sector, uint32_t open_mode, bool ignore_error)
{
    string filename(name);
    filename.push_back('.');
    filename.push_back('0' + sector);
    int32_t handle = -1;
    int ret = sl_FsOpen((uint8_t *)filename.c_str(), open_mode, NULL, &handle);
    if (!ignore_error)
    {
        SlCheckResult(ret);
        HASSERT(handle >= 0);
    }
    return handle;
}

void CC32xxEEPROMEmulation::write(
    unsigned int index, const void *buf, size_t len)
{
    // Boundary checks are performed by the EEPROM class.
    if (memcmp(data_ + index, buf, len) == 0) {
        return;
    }
    memcpy(data_ + index, buf, len);
    isDirty_ = 1;
    eeprom_updated_notification();
}

void CC32xxEEPROMEmulation::read(unsigned int index, void *buf, size_t len)
{
    // Boundary checks are performed by the EEPROM class.
    memcpy(buf, data_ + index, len);
}
<|endoftext|>


<commit_before>#include "cuda/cudaTextureResource.h"

#include "cuda/cudadefs.h"
#include "cuda/helper_math.h"
#include "cuda/cudautil.h"
#include "cuda/cudamemory.h"

namespace idaten
{
    void CudaLeyered2DTexture::init(
        std::vector<const aten::vec4*>& p,
        uint32_t width,
        uint32_t height)
    {
        int layerNum = static_cast<int>(p.size());
        int imgSize = width * height;

        auto totalSize = imgSize * layerNum;
        std::vector<aten::vec4> hostMem(totalSize);

        for (int n = 0; n < layerNum; n++) {
            for (int i = 0; i < imgSize; i++) {
                hostMem[n * imgSize + i] = p[n][i];
            }
        }

        auto bytes = imgSize * layerNum * sizeof(float4);

        // allocate device memory for result.
        float4* deviceMem = nullptr;
        checkCudaErrors(cudaMalloc((void **)&deviceMem, bytes));

        // allocate array and copy image data.
        cudaChannelFormatDesc channelDesc = cudaCreateChannelDesc<float4>();

        checkCudaErrors(
            cudaMalloc3DArray(
                &m_array,
                &channelDesc,
                make_cudaExtent(width, height, layerNum),
                cudaArrayLayered));

        cudaMemcpy3DParms memcpyParams = { 0 };
        memcpyParams.srcPos = make_cudaPos(0, 0, 0);
        memcpyParams.dstPos = make_cudaPos(0, 0, 0);
        memcpyParams.srcPtr = make_cudaPitchedPtr(&hostMem[0], width * sizeof(float4), width, height);
        memcpyParams.dstArray = m_array;
        memcpyParams.extent = make_cudaExtent(width, height, layerNum);
        memcpyParams.kind = cudaMemcpyHostToDevice;
        checkCudaErrors(cudaMemcpy3DAsync(&memcpyParams));

        memset(&m_resDesc, 0, sizeof(m_resDesc));
        m_resDesc.resType = cudaResourceTypeArray;
        m_resDesc.res.array.array = m_array;
    }

    cudaTextureObject_t CudaLeyered2DTexture::bind()
    {
        if (m_tex == 0) {
            // Make texture description:
            cudaTextureDesc tex_desc = {};
            tex_desc.readMode = cudaReadModeElementType;
            tex_desc.filterMode = cudaFilterModePoint;
            tex_desc.addressMode[0] = cudaAddressModeWrap;
            tex_desc.addressMode[1] = cudaAddressModeWrap;
            tex_desc.normalizedCoords = 0;

            checkCudaErrors(cudaCreateTextureObject(&m_tex, &m_resDesc, &tex_desc, nullptr));
        }

        return m_tex;
    }
}<commit_msg>Fix wrong flag value<commit_after>#include "cuda/cudaTextureResource.h"

#include "cuda/cudadefs.h"
#include "cuda/helper_math.h"
#include "cuda/cudautil.h"
#include "cuda/cudamemory.h"

namespace idaten
{
    void CudaLeyered2DTexture::init(
        std::vector<const aten::vec4*>& p,
        uint32_t width,
        uint32_t height)
    {
        int layerNum = static_cast<int>(p.size());
        int imgSize = width * height;

        auto totalSize = imgSize * layerNum;
        std::vector<aten::vec4> hostMem(totalSize);

        for (int n = 0; n < layerNum; n++) {
            for (int i = 0; i < imgSize; i++) {
                hostMem[n * imgSize + i] = p[n][i];
            }
        }

        auto bytes = imgSize * layerNum * sizeof(float4);

        // allocate device memory for result.
        float4* deviceMem = nullptr;
        checkCudaErrors(cudaMalloc((void **)&deviceMem, bytes));

        // allocate array and copy image data.
        cudaChannelFormatDesc channelDesc = cudaCreateChannelDesc<float4>();

        checkCudaErrors(
            cudaMalloc3DArray(
                &m_array,
                &channelDesc,
                make_cudaExtent(width, height, layerNum),
                cudaArrayLayered));

        cudaMemcpy3DParms memcpyParams = { 0 };
        memcpyParams.srcPos = make_cudaPos(0, 0, 0);
        memcpyParams.dstPos = make_cudaPos(0, 0, 0);
        memcpyParams.srcPtr = make_cudaPitchedPtr(&hostMem[0], width * sizeof(float4), width, height);
        memcpyParams.dstArray = m_array;
        memcpyParams.extent = make_cudaExtent(width, height, layerNum);
        memcpyParams.kind = cudaMemcpyHostToDevice;
        checkCudaErrors(cudaMemcpy3DAsync(&memcpyParams));

        memset(&m_resDesc, 0, sizeof(m_resDesc));
        m_resDesc.resType = cudaResourceTypeArray;
        m_resDesc.res.array.array = m_array;
    }

    cudaTextureObject_t CudaLeyered2DTexture::bind()
    {
        if (m_tex == 0) {
            // Make texture description:
            cudaTextureDesc tex_desc = {};
            tex_desc.readMode = cudaReadModeElementType;
            tex_desc.filterMode = cudaFilterModePoint;
            tex_desc.addressMode[0] = cudaAddressModeWrap;
            tex_desc.addressMode[1] = cudaAddressModeWrap;
            tex_desc.normalizedCoords = true;

            checkCudaErrors(cudaCreateTextureObject(&m_tex, &m_resDesc, &tex_desc, nullptr));
        }

        return m_tex;
    }
}<|endoftext|>


<commit_before>#include "../checkpoint/checkpoint.h"
#include "myrandom/myrand.h"
#include <algorithm>                            // for std::shuffle
#include <cstdint>                              // for std::int32_t
#include <iostream>                             // for std::cout
#include <random>                               // for std::mt19937
#include <utility>                              // for std::make_pair
#include <vector>                               // for std::vector
#include <boost/algorithm/cxx11/iota.hpp>       // for boost::algorithm::iota
#include <boost/format.hpp>                     // for boost::format
#include <boost/range/algorithm.hpp>            // for boost::find, boost::transform
#include <tbb/concurrent_vector.h>              // for tbb::concurrent_vector
#include <tbb/parallel_for.h>                   // for tbb::parallel_for

namespace {
    // ビンゴボードのマス数
    static auto constexpr BOARDSIZE = 25U;

    // モンテカルロシミュレーションの試行回数
    static auto constexpr MCMAX = 1000000U;

    // 行・列の総数
    static auto constexpr ROWCOLUMNSIZE = 10U;

    //! A typedef.
    /*!
        そのマスに書かれてある番号と、そのマスが当たったかどうかを示すフラグ
        のstd::pair
    */
    using mypair = std::pair<std::int32_t, bool>;

    //! A typedef.
    /*!
        行・列が埋まるまでに要した回数と、その時点で埋まったマスのstd::pair
    */
    using mypair2 = std::pair<std::int32_t, std::int32_t>;

    //! A function.
    /*!
        ビンゴボードを生成する
        \return ビンゴボードが格納された可変長配列
    */
    auto makeBoard();

    //! A function.
    /*!
        モンテカルロ・シミュレーションを行う
        \return モンテカルロ法の結果が格納された二次元可変長配列
    */
    std::vector< std::vector<mypair2> > montecarlo();

    //! A function.
    /*!
        モンテカルロ・シミュレーションの実装
        \return モンテカルロ法の結果が格納された可変長配列
    */
    std::vector<mypair2> montecarloImpl();

    //! A function.
    /*!
        モンテカルロ・シミュレーションをTBBで並列化して行う
        \return モンテカルロ法の結果が格納された可変長配列
    */
    tbb::concurrent_vector< std::vector<mypair2> > montecarloTBB();
}

int main()
{
    checkpoint::CheckPoint cp;

    cp.checkpoint("処理開始", __LINE__);

    // モンテカルロ・シミュレーションの結果を代入
    auto const mcresult(montecarlo());

    cp.checkpoint("並列化無効", __LINE__);

    // TBBで並列化したモンテカルロ・シミュレーションの結果を代入
    auto const mcresult2(montecarloTBB());

    cp.checkpoint("並列化有効", __LINE__);

    // モンテカルロ・シミュレーションの平均試行回数の結果を格納した可変長配列
    std::vector<double> trialavg(ROWCOLUMNSIZE);

    // モンテカルロ・シミュレーションのi回目の試行で、埋まっているマスの数を格納した可変長配列
    std::vector<double> fillavg(ROWCOLUMNSIZE);

    // 行・列の総数分繰り返す
    for (auto i = 0U; i < ROWCOLUMNSIZE; i++) {
        // 総和を0で初期化
        auto trialsum = 0;
        auto fillsum = 0;

        // 試行回数分繰り返す
        for (auto j = 0U; j < MCMAX; j++) {
            // j回目の結果を加える
            trialsum += mcresult[j][i].first;
            fillsum += mcresult[j][i].second;
        }

        // 平均を算出してi行・列目のtrialavg、fillavgに代入
        trialavg[i] = static_cast<double>(trialsum) / static_cast<double>(MCMAX);
        fillavg[i] = static_cast<double>(fillsum) / static_cast<double>(MCMAX);
    }

    for (auto i = 0U; i < ROWCOLUMNSIZE; i++) {
        auto const efficiency = trialavg[i] / static_cast<double>(i + 1);
        std::cout
            << boost::format("%d個目に必要な平均試行回数：%.1f回, 効率 = %.1f（回/個）, ")
            % (i + 1) % trialavg[i] % efficiency
            << boost::format("埋まっているマスの平均個数：%.1f個\n")
            % fillavg[i];
    }

    cp.checkpoint_print();

    return 0;
}

namespace {
    auto makeBoard()
    {
        // 仮のビンゴボードを生成
        std::vector<std::int32_t> boardtmp(BOARDSIZE);

        // 仮のビンゴボードに1～25の数字を代入
        boost::algorithm::iota(boardtmp, 1);

        // 仮のビンゴボードの数字をシャッフル
        std::shuffle(boardtmp.begin(), boardtmp.end(), std::mt19937());

        // ビンゴボードを生成
        std::vector<mypair> board(BOARDSIZE);

        // 仮のビンゴボードからビンゴボードを生成する
        boost::transform(
            boardtmp,
            board.begin(),
            [](auto n) { return std::make_pair(n, false); });

        // ビンゴボードを返す
        return board;
    }

    std::vector< std::vector<mypair2> > montecarlo()
    {
        // モンテカルロ・シミュレーションの結果を格納するための二次元可変長配列
        std::vector< std::vector<mypair2> > mcresult;

        // MCMAX個の容量を確保
        mcresult.reserve(MCMAX);

        // 試行回数分繰り返す
        for (auto i = 0U; i < MCMAX; i++) {
            // モンテカルロ・シミュレーションの結果を代入
            mcresult.push_back(montecarloImpl());
        }

        // モンテカルロ・シミュレーションの結果を返す
        return mcresult;
    }

    std::vector<mypair2> montecarloImpl()
    {
        // ビンゴボードを生成
        auto board(makeBoard());

        // 自作乱数クラスを初期化
        myrandom::MyRand mr(1, BOARDSIZE);

        // その行・列が既に埋まっているかどうかを格納する可変長配列
        // ROWCOLUMNSIZE個の要素をfalseで初期化
        std::vector<bool> rcfill(ROWCOLUMNSIZE, false);

        // 行・列が埋まるまでに要した回数と、その時点で埋まったマスを格納した
        // 可変長配列
        std::vector< mypair2 > fillnum;

        // ROWCOLUMNSIZE個の容量を確保
        fillnum.reserve(ROWCOLUMNSIZE);

        // その時点で埋まっているマスを計算するためのラムダ式
        auto const sum = [](const std::vector< mypair > & vec)
        {
            auto cnt = 0;
            for (auto & e : vec) {
                if (e.second) {
                    cnt++;
                }
            }

            return cnt;
        };

        // 無限ループ
        for (auto i = 1; ; i++) {
            // 乱数で得た数字で、かつまだ当たってないマスを検索
            auto itr = boost::find(board, std::make_pair(mr.myrand(), false));

            // そのようなマスがあった
            if (itr != board.end()) {
                // そのマスは当たったとし、フラグをtrueにする
                itr->second = true;
            }
            // そのようなマスがなかった
            else {
                //ループ続行
                continue;
            }

            // 各行・列が埋まったかどうかをチェック
            for (auto j = 0; j < 5; j++) {
                // 行をチェック
                if (board[5 * j].second &&
                    board[5 * j + 1].second &&
                    board[5 * j + 2].second &&
                    board[5 * j + 3].second &&
                    board[5 * j + 4].second &&
                    // その行は既に埋まっているかどうか
                    !rcfill[j]) {

                    // その行は埋まったとして、フラグをtrueにする
                    rcfill[j] = true;

                    // 要した試行回数と、その時点で埋まったマスの数を格納
                    fillnum.push_back(std::make_pair(i, sum(board)));
                }

                // 列をチェック
                if (board[j].second &&
                    board[j + 5].second &&
                    board[j + 10].second &&
                    board[j + 15].second &&
                    board[j + 20].second &&
                    // その列は既に埋まっているかどうか
                    !rcfill[j + 5]) {

                    // その列は埋まったとして、フラグをtrueにする
                    rcfill[j + 5] = true;

                    // 要した試行回数と、その時点で埋まったマスの数を格納
                    fillnum.push_back(std::make_pair(i, sum(board)));
                }
            }

            // 全ての行・列が埋まったかどうか
            if (fillnum.size() == ROWCOLUMNSIZE) {
                // 埋まったのでループ脱出
                break;
            }
        }

        // 要した試行関数の可変長配列を返す
        return fillnum;
    }

    tbb::concurrent_vector< std::vector<mypair2> > montecarloTBB()
    {
        // モンテカルロ・シミュレーションの結果を格納するための二次元可変長配列
        // 複数のスレッドが同時にアクセスする可能性があるためtbb::concurrent_vectorを使う
        tbb::concurrent_vector< std::vector<mypair2> > mcresult;

        // MCMAX個の容量を確保
        mcresult.reserve(MCMAX);

        // MCMAX回のループを並列化して実行
        tbb::parallel_for(
            std::uint32_t(0),
            MCMAX,
            std::uint32_t(1),
            [&mcresult](auto) { mcresult.push_back(montecarloImpl()); });

        // モンテカルロ・シミュレーションの結果を返す
        return mcresult;
    }
}
<commit_msg>C++14で書き直した<commit_after>#include "../checkpoint/checkpoint.h"
#include "myrandom/myrand.h"
#include <algorithm>                            // for std::shuffle
#include <cstdint>                              // for std::int32_t
#include <iostream>                             // for std::cout
#include <random>                               // for std::mt19937
#include <utility>                              // for std::make_pair
#include <vector>                               // for std::vector
#include <boost/algorithm/cxx11/iota.hpp>       // for boost::algorithm::iota
#include <boost/format.hpp>                     // for boost::format
#include <boost/range/algorithm.hpp>            // for boost::find, boost::transform
#include <tbb/concurrent_vector.h>              // for tbb::concurrent_vector
#include <tbb/parallel_for.h>                   // for tbb::parallel_for

namespace {
    // ビンゴボードのマス数
    static auto constexpr BOARDSIZE = 25U;

    // モンテカルロシミュレーションの試行回数
    static auto constexpr MCMAX = 1000000U;

    // 行・列の総数
    static auto constexpr ROWCOLUMNSIZE = 10U;

    //! A typedef.
    /*!
        そのマスに書かれてある番号と、そのマスが当たったかどうかを示すフラグ
        のstd::pair
    */
    using mypair = std::pair<std::int32_t, bool>;

    //! A typedef.
    /*!
        行・列が埋まるまでに要した回数と、その時点で埋まったマスのstd::pair
    */
    using mypair2 = std::pair<std::int32_t, std::int32_t>;

    //! A function.
    /*!
        ビンゴボードを生成する
        \return ビンゴボードが格納された可変長配列
    */
    auto makeBoard();

    //! A function.
    /*!
        モンテカルロ・シミュレーションを行う
        \return モンテカルロ法の結果が格納された二次元可変長配列
    */
    std::vector< std::vector<mypair2> > montecarlo();

    //! A function.
    /*!
        モンテカルロ・シミュレーションの実装
        \return モンテカルロ法の結果が格納された可変長配列
    */
    std::vector<mypair2> montecarloImpl();

    //! A function.
    /*!
        モンテカルロ・シミュレーションをTBBで並列化して行う
        \return モンテカルロ法の結果が格納された可変長配列
    */
    tbb::concurrent_vector< std::vector<mypair2> > montecarloTBB();
}

int main()
{
    checkpoint::CheckPoint cp;

    cp.checkpoint("処理開始", __LINE__);

    // モンテカルロ・シミュレーションの結果を代入
    auto const mcresult(montecarlo());

    cp.checkpoint("並列化無効", __LINE__);

    // TBBで並列化したモンテカルロ・シミュレーションの結果を代入
    auto const mcresult2(montecarloTBB());

    cp.checkpoint("並列化有効", __LINE__);

    // モンテカルロ・シミュレーションの平均試行回数の結果を格納した可変長配列
    std::vector<double> trialavg(ROWCOLUMNSIZE);

    // モンテカルロ・シミュレーションのi回目の試行で、埋まっているマスの数を格納した可変長配列
    std::vector<double> fillavg(ROWCOLUMNSIZE);

    // 行・列の総数分繰り返す
    for (auto i = 0U; i < ROWCOLUMNSIZE; i++) {
        // 総和を0で初期化
        auto trialsum = 0;
        auto fillsum = 0;

        // 試行回数分繰り返す
        for (auto j = 0U; j < MCMAX; j++) {
            // j回目の結果を加える
            trialsum += mcresult[j][i].first;
            fillsum += mcresult[j][i].second;
        }

        // 平均を算出してi行・列目のtrialavg、fillavgに代入
        trialavg[i] = static_cast<double>(trialsum) / static_cast<double>(MCMAX);
        fillavg[i] = static_cast<double>(fillsum) / static_cast<double>(MCMAX);
    }

    for (auto i = 0U; i < ROWCOLUMNSIZE; i++) {
        auto const efficiency = trialavg[i] / static_cast<double>(i + 1);
        std::cout
            << boost::format("%d個目に必要な平均試行回数：%.1f回, 効率 = %.1f（回/個）, ")
            % (i + 1) % trialavg[i] % efficiency
            << boost::format("埋まっているマスの平均個数：%.1f個\n")
            % fillavg[i];
    }

    cp.checkpoint_print();

    return 0;
}

namespace {
    auto makeBoard()
    {
        // 仮のビンゴボードを生成
        std::vector<std::int32_t> boardtmp(BOARDSIZE);

        // 仮のビンゴボードに1～25の数字を代入
        boost::algorithm::iota(boardtmp, 1);

        // 仮のビンゴボードの数字をシャッフル
        std::shuffle(boardtmp.begin(), boardtmp.end(), std::mt19937());

        // ビンゴボードを生成
        std::vector<mypair> board(BOARDSIZE);

        // 仮のビンゴボードからビンゴボードを生成する
        boost::transform(
            boardtmp,
            board.begin(),
            [](auto n) { return std::make_pair(n, false); });

        // ビンゴボードを返す
        return board;
    }

    std::vector< std::vector<mypair2> > montecarlo()
    {
        // モンテカルロ・シミュレーションの結果を格納するための二次元可変長配列
        std::vector< std::vector<mypair2> > mcresult;

        // MCMAX個の容量を確保
        mcresult.reserve(MCMAX);

        // 試行回数分繰り返す
        for (auto i = 0U; i < MCMAX; i++) {
            // モンテカルロ・シミュレーションの結果を代入
            mcresult.push_back(montecarloImpl());
        }

        // モンテカルロ・シミュレーションの結果を返す
        return mcresult;
    }

    std::vector<mypair2> montecarloImpl()
    {
        // ビンゴボードを生成
        auto board(makeBoard());

        // 自作乱数クラスを初期化
        myrandom::MyRand mr(1, BOARDSIZE);

        // その行・列が既に埋まっているかどうかを格納する可変長配列
        // ROWCOLUMNSIZE個の要素をfalseで初期化
        std::vector<bool> rcfill(ROWCOLUMNSIZE, false);

        // 行・列が埋まるまでに要した回数と、その時点で埋まったマスを格納した
        // 可変長配列
        std::vector< mypair2 > fillnum;

        // ROWCOLUMNSIZE個の容量を確保
        fillnum.reserve(ROWCOLUMNSIZE);

        // その時点で埋まっているマスを計算するためのラムダ式
        auto const sum = [](auto const & vec)
        {
            auto cnt = 0;
            for (auto & e : vec) {
                if (e.second) {
                    cnt++;
                }
            }

            return cnt;
        };

        // 無限ループ
        for (auto i = 1; ; i++) {
            // 乱数で得た数字で、かつまだ当たってないマスを検索
            auto itr = boost::find(board, std::make_pair(mr.myrand(), false));

            // そのようなマスがあった
            if (itr != board.end()) {
                // そのマスは当たったとし、フラグをtrueにする
                itr->second = true;
            }
            // そのようなマスがなかった
            else {
                //ループ続行
                continue;
            }

            // 各行・列が埋まったかどうかをチェック
            for (auto j = 0; j < 5; j++) {
                // 行をチェック
                if (board[5 * j].second &&
                    board[5 * j + 1].second &&
                    board[5 * j + 2].second &&
                    board[5 * j + 3].second &&
                    board[5 * j + 4].second &&
                    // その行は既に埋まっているかどうか
                    !rcfill[j]) {

                    // その行は埋まったとして、フラグをtrueにする
                    rcfill[j] = true;

                    // 要した試行回数と、その時点で埋まったマスの数を格納
                    fillnum.push_back(std::make_pair(i, sum(board)));
                }

                // 列をチェック
                if (board[j].second &&
                    board[j + 5].second &&
                    board[j + 10].second &&
                    board[j + 15].second &&
                    board[j + 20].second &&
                    // その列は既に埋まっているかどうか
                    !rcfill[j + 5]) {

                    // その列は埋まったとして、フラグをtrueにする
                    rcfill[j + 5] = true;

                    // 要した試行回数と、その時点で埋まったマスの数を格納
                    fillnum.push_back(std::make_pair(i, sum(board)));
                }
            }

            // 全ての行・列が埋まったかどうか
            if (fillnum.size() == ROWCOLUMNSIZE) {
                // 埋まったのでループ脱出
                break;
            }
        }

        // 要した試行関数の可変長配列を返す
        return fillnum;
    }

    tbb::concurrent_vector< std::vector<mypair2> > montecarloTBB()
    {
        // モンテカルロ・シミュレーションの結果を格納するための二次元可変長配列
        // 複数のスレッドが同時にアクセスする可能性があるためtbb::concurrent_vectorを使う
        tbb::concurrent_vector< std::vector<mypair2> > mcresult;

        // MCMAX個の容量を確保
        mcresult.reserve(MCMAX);

        // MCMAX回のループを並列化して実行
        tbb::parallel_for(
            std::uint32_t(0),
            MCMAX,
            std::uint32_t(1),
            [&mcresult](auto) { mcresult.push_back(montecarloImpl()); });

        // モンテカルロ・シミュレーションの結果を返す
        return mcresult;
    }
}
<|endoftext|>


<commit_before>/*$Id$
 *
 * This source file is a part of the Berlin Project.
 * Copyright (C) 1999 Stefan Seefeld <stefan@berlin-consortium.org>
 * http://www.berlin-consortium.org
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Library General Public
 * License as published by the Free Software Foundation; either
 * version 2 of the License, or (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Library General Public License for more details.
 *
 * You should have received a copy of the GNU Library General Public
 * License along with this library; if not, write to the
 * Free Software Foundation, Inc., 675 Mass Ave, Cambridge,
 * MA 02139, USA.
 */

#include "Desktop/WindowImpl.hh"
#include <Berlin/Vertex.hh>
#include <Prague/Sys/Tracer.hh>

using namespace Prague;

class Mover : public WindowImpl::Manipulator
{
public:
  virtual void execute(const CORBA::Any &any)
    {
      if (CORBA::is_nil(handle)) return;
      Vertex *delta;
      if (any >>= delta)
	{
 	  Vertex p = handle->position();
	  handle->position(p + *delta);
	}
      else  cerr << "Mover::execute : wrong message type !" << endl;
    }
};

class Resizer : public WindowImpl::Manipulator
{
public:
  virtual void execute(const CORBA::Any &any)
    {
      if (CORBA::is_nil(handle)) return;
      Vertex *delta;
      if (any >>= delta)
	{
 	  Vertex s = handle->size();
          Graphic::Requisition r;
          handle->child()->request(r);
          if (r.x.defined)
            {
              if (delta->x > 0.) s.x = min(s.x + delta->x, r.x.maximum);
              else s.x = max(s.x + delta->x, r.x.minimum);
            }
          else s.x += delta->x;
          if (r.y.defined)
            {
              if (delta->y > 0.) s.y = min(s.y + delta->y, r.y.maximum);
              else s.y = max(s.y + delta->y, r.y.minimum);
            }
          else s.y += delta->y;
	  handle->size(s);
	}
      else cerr << "Resizer::execute : wrong message type !" << endl;
    }
};

class MoveResizer : public WindowImpl::Manipulator
{
public:
  MoveResizer(Alignment x, Alignment y, CORBA::Short b) : xalign(x), yalign(y), border(b) {}
  virtual void execute(const CORBA::Any &any)
    {
      Trace trace("MoveResizer::execute");
      if (CORBA::is_nil(handle)) return;
      Vertex *vertex;
      if (any >>= vertex)
	{
          Graphic::Requisition r;
          handle->child()->request(r);
 	  Vertex pos = handle->position();
 	  Vertex size = handle->size();
	  Vertex p = pos, s = size;
	  if (border & Window::left && xalign != 0.)
	    {
	      s.x = min(r.x.maximum, max(r.x.minimum, size.x - vertex->x/xalign));
	      p.x = pos.x - xalign * (s.x - size.x);
	    }
	  else if (border & Window::right && xalign != 1.)
	    {
	      s.x = min(r.x.maximum, max(r.x.minimum, size.x + vertex->x/(1.-xalign)));
	      p.x = pos.x - xalign * (s.x - size.x);
	    }
	  if (border & Window::top && yalign != 0.)
	    {
	      s.y = min(r.y.maximum, max(r.y.minimum, size.y - vertex->y/yalign));
	      p.y = pos.y - yalign * (s.y - size.y);
	    }
	  else if (border & Window::bottom && yalign != 1.)
	    {
	      s.y = min(r.y.maximum, max(r.y.minimum, size.y + vertex->y/(1.-yalign)));
	      p.y = pos.y - yalign * (s.y - size.y);
	    }
	  handle->parent()->begin();
	  handle->position(p);
	  handle->size(s);
	  handle->parent()->end();
	}
      else cerr << "MoveResizer::execute : wrong message type !" << endl;
    }
private:
  Alignment xalign, yalign;
  CORBA::Short border;
};

class Relayerer : public WindowImpl::Manipulator
{
public:
  virtual void execute(const CORBA::Any &any)
    {
      if (CORBA::is_nil(handle)) return;
      Stage::Index i;
      if (any >>= i)
	{
	  handle->layer(i);
	}
      else cerr << "Relayerer::execute : wrong message type !" << endl;
    }
};

void WindowImpl::Mapper::execute(const CORBA::Any &)
{
  if (flag) window->map();
  else window->unmap();
}

WindowImpl::WindowImpl()
  : ControllerImpl(false), unmapped(0), manipulators(3), mapper(0)
{
  manipulators[0] = new Mover;
  manipulators[0]->_obj_is_ready(_boa());
  manipulators[1] = new Resizer;
  manipulators[1]->_obj_is_ready(_boa());
  manipulators[2] = new Relayerer;
  manipulators[2]->_obj_is_ready(_boa());
  mapper = new Mapper(this, true);
  mapper->_obj_is_ready(_boa());
  unmapper = new Mapper(this, false);
  unmapper->_obj_is_ready(_boa());
}

WindowImpl::~WindowImpl()
{
  cout << "WindowImpl::~WindowImpl" << endl;
  for (mtable_t::iterator i = manipulators.begin(); i != manipulators.end(); i++)
    (*i)->_dispose();
  mapper->_dispose();
  unmapper->_dispose();
}

// void WindowImpl::needResize()
// {
// }

/*
 * cache the focus holding controllers so we can restore them when the window
 * receives focus again...
 */
CORBA::Boolean WindowImpl::requestFocus(Controller_ptr c, Input::Device d)
{
  if (unmapped) return false;
  Controller_var parent = parentController();
  if (CORBA::is_nil(parent)) return false;
  if (parent->requestFocus(c, d))
    {
      if (focus.size() <= d) focus.resize(d + 1);
      focus[d] = Controller::_duplicate(c);
      return true;
    }
  else return false;
}

void WindowImpl::insert(Desktop_ptr desktop, bool mapped)
{
  Trace trace("WindowImpl::insert");
  Vertex position, size;
  position.x = position.y = 1000., position.z = 0.;
  Graphic::Requisition r;
  request(r);
  size.x = r.x.natural, size.y = r.y.natural, size.z = 0;
  unmapped = new UnmappedStageHandle(desktop, Graphic_var(_this()), position, size, 0);
  unmapped->_obj_is_ready(_boa());
  handle = StageHandle_var(unmapped->_this());
  if (mapped) map();
}

Command_ptr WindowImpl::move() { return manipulators[0]->_this();}
Command_ptr WindowImpl::resize() { return manipulators[1]->_this();}
Command_ptr WindowImpl::moveResize(Alignment x, Alignment y, CORBA::Short b)
{
  manipulators.push_back(new MoveResizer(x, y, b));
  manipulators.back()->_obj_is_ready(_boa());
  return manipulators.back()->_this();
}
Command_ptr WindowImpl::relayer() { return manipulators[2]->_this();}
Command_ptr WindowImpl::map(CORBA::Boolean f)
{
  return f ? mapper->_this() : unmapper->_this();
}

// void WindowImpl::pick(PickTraversal_ptr traversal)
// {
//   SectionLog section("WindowImpl::pick");
//   traversal->enterController(Controller_var(_this()));
//   MonoGraphic::traverse(traversal);
//   traversal->leaveController();
// }

void WindowImpl::map()
{
  Trace trace("WindowImpl::map");
  MutexGuard guard(mutex);
  if (!unmapped) return;
  Stage_var stage = handle->parent();
  stage->begin();
  StageHandle_var tmp = stage->insert(Graphic_var(_this()), handle->position(), handle->size(), handle->layer());
  stage->end();
  handle = tmp;
  for (mtable_t::iterator i = manipulators.begin(); i != manipulators.end(); i++)
    (*i)->bind(handle);
  unmapped->_dispose();
  unmapped = 0;
}

void WindowImpl::unmap()
{
  Trace trace("WindowImpl::unmap");
  MutexGuard guard(mutex);
  if (unmapped) return;
  unmapped = new UnmappedStageHandle(handle);
  unmapped->_obj_is_ready(_boa());
  handle->remove();
//  Stage_var stage = handle->parent();
//  stage->begin();
//  stage->remove(handle);
//  stage->end();
}
<commit_msg>windows now resize upon request<commit_after>/*$Id$
 *
 * This source file is a part of the Berlin Project.
 * Copyright (C) 1999 Stefan Seefeld <stefan@berlin-consortium.org>
 * http://www.berlin-consortium.org
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Library General Public
 * License as published by the Free Software Foundation; either
 * version 2 of the License, or (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Library General Public License for more details.
 *
 * You should have received a copy of the GNU Library General Public
 * License along with this library; if not, write to the
 * Free Software Foundation, Inc., 675 Mass Ave, Cambridge,
 * MA 02139, USA.
 */

#include "Desktop/WindowImpl.hh"
#include <Berlin/Vertex.hh>
#include <Prague/Sys/Tracer.hh>
#include <Warsaw/IO.hh>

using namespace Prague;

class Mover : public WindowImpl::Manipulator
{
public:
  virtual void execute(const CORBA::Any &any)
    {
      if (CORBA::is_nil(handle)) return;
      Vertex *delta;
      if (any >>= delta)
	{
 	  Vertex p = handle->position();
	  handle->position(p + *delta);
	}
      else  cerr << "Mover::execute : wrong message type !" << endl;
    }
};

class Resizer : public WindowImpl::Manipulator
{
public:
  virtual void execute(const CORBA::Any &any)
    {
      if (CORBA::is_nil(handle)) return;
      Vertex *delta;
      if (any >>= delta)
	{
 	  Vertex s = handle->size();
          Graphic::Requisition r;
          handle->child()->request(r);
          if (r.x.defined)
            {
              if (delta->x > 0.) s.x = min(s.x + delta->x, r.x.maximum);
              else s.x = max(s.x + delta->x, r.x.minimum);
            }
          else s.x += delta->x;
          if (r.y.defined)
            {
              if (delta->y > 0.) s.y = min(s.y + delta->y, r.y.maximum);
              else s.y = max(s.y + delta->y, r.y.minimum);
            }
          else s.y += delta->y;
	  handle->size(s);
	}
      else cerr << "Resizer::execute : wrong message type !" << endl;
    }
};

class MoveResizer : public WindowImpl::Manipulator
{
public:
  MoveResizer(Alignment x, Alignment y, CORBA::Short b) : xalign(x), yalign(y), border(b) {}
  virtual void execute(const CORBA::Any &any)
    {
      Trace trace("MoveResizer::execute");
      if (CORBA::is_nil(handle)) return;
      Vertex *vertex;
      if (any >>= vertex)
	{
          Graphic::Requisition r;
          handle->child()->request(r);
 	  Vertex pos = handle->position();
 	  Vertex size = handle->size();
	  Vertex p = pos, s = size;
	  if (border & Window::left && xalign != 0.)
	    {
	      s.x = min(r.x.maximum, max(r.x.minimum, size.x - vertex->x/xalign));
	      p.x = pos.x - xalign * (s.x - size.x);
	    }
	  else if (border & Window::right && xalign != 1.)
	    {
	      s.x = min(r.x.maximum, max(r.x.minimum, size.x + vertex->x/(1.-xalign)));
	      p.x = pos.x - xalign * (s.x - size.x);
	    }
	  if (border & Window::top && yalign != 0.)
	    {
	      s.y = min(r.y.maximum, max(r.y.minimum, size.y - vertex->y/yalign));
	      p.y = pos.y - yalign * (s.y - size.y);
	    }
	  else if (border & Window::bottom && yalign != 1.)
	    {
	      s.y = min(r.y.maximum, max(r.y.minimum, size.y + vertex->y/(1.-yalign)));
	      p.y = pos.y - yalign * (s.y - size.y);
	    }
	  handle->parent()->begin();
	  handle->position(p);
	  handle->size(s);
	  handle->parent()->end();
	}
      else cerr << "MoveResizer::execute : wrong message type !" << endl;
    }
private:
  Alignment xalign, yalign;
  CORBA::Short border;
};

class Relayerer : public WindowImpl::Manipulator
{
public:
  virtual void execute(const CORBA::Any &any)
    {
      if (CORBA::is_nil(handle)) return;
      Stage::Index i;
      if (any >>= i)
	{
	  handle->layer(i);
	}
      else cerr << "Relayerer::execute : wrong message type !" << endl;
    }
};

void WindowImpl::Mapper::execute(const CORBA::Any &)
{
  if (flag) window->map();
  else window->unmap();
}

WindowImpl::WindowImpl()
  : ControllerImpl(false), unmapped(0), manipulators(3), mapper(0)
{
  manipulators[0] = new Mover;
  manipulators[0]->_obj_is_ready(_boa());
  manipulators[1] = new Resizer;
  manipulators[1]->_obj_is_ready(_boa());
  manipulators[2] = new Relayerer;
  manipulators[2]->_obj_is_ready(_boa());
  mapper = new Mapper(this, true);
  mapper->_obj_is_ready(_boa());
  unmapper = new Mapper(this, false);
  unmapper->_obj_is_ready(_boa());
}

WindowImpl::~WindowImpl()
{
  cout << "WindowImpl::~WindowImpl" << endl;
  for (mtable_t::iterator i = manipulators.begin(); i != manipulators.end(); i++)
    (*i)->_dispose();
  mapper->_dispose();
  unmapper->_dispose();
}

void WindowImpl::needResize()
{
  Trace trace("WindowImpl::needResize");
  Vertex size = handle->size();
  Graphic::Requisition r;
  request(r);
  if (r.x.minimum <= size.x && r.x.maximum >= size.x && r.y.minimum <= size.y && r.y.maximum >= size.y)
    needRedraw();
  else
    {
      size.x = min(r.x.maximum, max(r.x.minimum, size.x));
      size.y = min(r.y.maximum, max(r.y.minimum, size.y));
      handle->size(size);
    }
}

/*
 * cache the focus holding controllers so we can restore them when the window
 * receives focus again...
 */
CORBA::Boolean WindowImpl::requestFocus(Controller_ptr c, Input::Device d)
{
  if (unmapped) return false;
  Controller_var parent = parentController();
  if (CORBA::is_nil(parent)) return false;
  if (parent->requestFocus(c, d))
    {
      if (focus.size() <= d) focus.resize(d + 1);
      focus[d] = Controller::_duplicate(c);
      return true;
    }
  else return false;
}

void WindowImpl::insert(Desktop_ptr desktop, bool mapped)
{
  Trace trace("WindowImpl::insert");
  Vertex position, size;
  position.x = position.y = 1000., position.z = 0.;
  Graphic::Requisition r;
  request(r);
  size.x = r.x.natural, size.y = r.y.natural, size.z = 0;
  unmapped = new UnmappedStageHandle(desktop, Graphic_var(_this()), position, size, 0);
  unmapped->_obj_is_ready(_boa());
  handle = StageHandle_var(unmapped->_this());
  if (mapped) map();
}

Command_ptr WindowImpl::move() { return manipulators[0]->_this();}
Command_ptr WindowImpl::resize() { return manipulators[1]->_this();}
Command_ptr WindowImpl::moveResize(Alignment x, Alignment y, CORBA::Short b)
{
  manipulators.push_back(new MoveResizer(x, y, b));
  manipulators.back()->_obj_is_ready(_boa());
  return manipulators.back()->_this();
}
Command_ptr WindowImpl::relayer() { return manipulators[2]->_this();}
Command_ptr WindowImpl::map(CORBA::Boolean f)
{
  return f ? mapper->_this() : unmapper->_this();
}

// void WindowImpl::pick(PickTraversal_ptr traversal)
// {
//   SectionLog section("WindowImpl::pick");
//   traversal->enterController(Controller_var(_this()));
//   MonoGraphic::traverse(traversal);
//   traversal->leaveController();
// }

void WindowImpl::map()
{
  Trace trace("WindowImpl::map");
  MutexGuard guard(mutex);
  if (!unmapped) return;
  Stage_var stage = handle->parent();
  stage->begin();
  StageHandle_var tmp = stage->insert(Graphic_var(_this()), handle->position(), handle->size(), handle->layer());
  stage->end();
  handle = tmp;
  for (mtable_t::iterator i = manipulators.begin(); i != manipulators.end(); i++)
    (*i)->bind(handle);
  unmapped->_dispose();
  unmapped = 0;
}

void WindowImpl::unmap()
{
  Trace trace("WindowImpl::unmap");
  MutexGuard guard(mutex);
  if (unmapped) return;
  unmapped = new UnmappedStageHandle(handle);
  unmapped->_obj_is_ready(_boa());
  handle->remove();
//  Stage_var stage = handle->parent();
//  stage->begin();
//  stage->remove(handle);
//  stage->end();
}
<|endoftext|>


<commit_before>#include <bits/stdc++.h>
using namespace std;

int  T;
int main(){
    int i, j;

    return 0;
}
<commit_msg>Delete CJ2015-QUALITIFICATION-B.cpp<commit_after><|endoftext|>


<commit_before>// Copyright 2013 Tanel Lebedev

#include "./main.h"

#include <sstream>

#include "Poco/Message.h"
#include "Poco/Util/Application.h"

#define ERRLEN 1024

namespace command_line_client {

    void Main::usage() {
        std::cout << "Recognized commands are: "
            "sync, start, stop, status, pushable, list, continue, listen"
            << std::endl;
    }

    void Main::defineOptions(Poco::Util::OptionSet& options) {
        Poco::Util::Application::defineOptions(options);
        options.addOption(Poco::Util::Option(
            "verbose", "v", "verbose logging, to the console"));
    }

    std::string KopsikModelChangeToString(
            KopsikModelChange &change) {
        std::stringstream ss;
        ss  << "model_type=" << change.ModelType
            << ", change_type=" << change.ChangeType
            << ", model_id=" << change.ModelID
            << ", GUID=" << change.GUID;
        return ss.str();
    }

    std::string KopsikTimeEntryViewItemToString(
            KopsikTimeEntryViewItem *item) {
        std::stringstream ss;
        ss << "description: " << item->Description;
        if (item->Project) {
            ss << " project: " << item->Project;
        }
        if (item->Duration) {
            ss << " duration: " << item->Duration;
        }
        return ss.str();
    }

    void on_view_item_change(kopsik_api_result result,
            char *err_string,
            int unsigned err_len,
            KopsikModelChange *change) {
        if (KOPSIK_API_SUCCESS != result) {
            std::string err("");
            err.append(err_string, err_len);
            std::cerr << "on_view_item_change error! "
                << err << std::endl;
            free(err_string);
            return;
        }
        std::cout << "on_view_item_change "
            << KopsikModelChangeToString(*change)
            << std::endl;
    }

    int Main::main(const std::vector<std::string>& args) {
        if (args.empty()) {
            usage();
            return Poco::Util::Application::EXIT_USAGE;
        }

        char* apiToken = getenv("TOGGL_API_TOKEN");
        if (!apiToken) {
            std::cerr << "Please set TOGGL_API_TOKEN in environment" <<
                std::endl;
            return Poco::Util::Application::EXIT_USAGE;
        }

        kopsik_set_db_path(ctx, "kopsik.db");
        kopsik_set_log_path(ctx, "kopsik.log");

        Poco::ErrorHandler::set(this);

        // Start session in lib
        char err[ERRLEN];
        std::fill(err, err + ERRLEN, 0);
        if (KOPSIK_API_SUCCESS != kopsik_set_api_token(
                ctx, err, ERRLEN, apiToken)) {
            std::cerr << err << std::endl;
            return Poco::Util::Application::EXIT_SOFTWARE;
        }

        // Load user that is referenced by the session
        KopsikUser *user = kopsik_user_init();
        if (KOPSIK_API_SUCCESS != kopsik_current_user(
                ctx, err, ERRLEN, user)) {
            std::cerr << err << std::endl;
            return Poco::Util::Application::EXIT_SOFTWARE;
        }
        kopsik_user_clear(user);

        if ("sync" == args[0]) {
            if (KOPSIK_API_SUCCESS != kopsik_sync(ctx, err, ERRLEN, 1)) {
                std::cerr << err << std::endl;
                return Poco::Util::Application::EXIT_SOFTWARE;
            }
            std::cout << "Synced." << std::endl;
            return Poco::Util::Application::EXIT_OK;
        }

        if ("status" == args[0]) {
            KopsikTimeEntryViewItem *te = kopsik_time_entry_view_item_init();
            int found(0);
            if (KOPSIK_API_SUCCESS != kopsik_running_time_entry_view_item(
                    ctx, err, ERRLEN, te, &found)) {
                std::cerr << err << std::endl;
                kopsik_time_entry_view_item_clear(te);
                return Poco::Util::Application::EXIT_SOFTWARE;
            }
            if (found) {
                std::cout << "Tracking: " << te->Description << std::endl;
            } else {
                std::cout << "Not tracking." << std::endl;
            }
            kopsik_time_entry_view_item_clear(te);
            return Poco::Util::Application::EXIT_OK;
        }

        if ("pushable" == args[0]) {
            KopsikPushableModelStats stats;
            if (KOPSIK_API_SUCCESS != kopsik_pushable_models(
                    ctx, err, ERRLEN, &stats)) {
                std::cerr << err << std::endl;
                return Poco::Util::Application::EXIT_SOFTWARE;
            }
            std::cout << stats.TimeEntries << " pushable time entries." << std::endl;
            return Poco::Util::Application::EXIT_OK;
        }

        if ("start" == args[0]) {
            KopsikTimeEntryViewItem *te = kopsik_time_entry_view_item_init();
            if (KOPSIK_API_SUCCESS != kopsik_start(
                    ctx, err, ERRLEN, "New time entry", te)) {
                std::cerr << err << std::endl;
                kopsik_time_entry_view_item_clear(te);
                return Poco::Util::Application::EXIT_SOFTWARE;
            }
            if (KOPSIK_API_SUCCESS != kopsik_push(ctx, err, ERRLEN)) {
                std::cerr << err << std::endl;
            }
            if (te->Description) {
                std::cout << "Started: " << te->Description << std::endl;
            } else {
                std::cout << "Started." << std::endl;
            }
            kopsik_time_entry_view_item_clear(te);
            return Poco::Util::Application::EXIT_OK;
        }

        if ("stop" == args[0]) {
            KopsikTimeEntryViewItem *te = kopsik_time_entry_view_item_init();
            if (KOPSIK_API_SUCCESS != kopsik_stop(
                    ctx, err, ERRLEN, te)) {
                std::cerr << err << std::endl;
                kopsik_time_entry_view_item_clear(te);
                return Poco::Util::Application::EXIT_SOFTWARE;
            }
            if (KOPSIK_API_SUCCESS != kopsik_push(ctx, err, ERRLEN)) {
                std::cerr << err << std::endl;
            }
            if (te->Description) {
                std::cout << "Stopped: " << te->Description << std::endl;
            } else {
                std::cout << "Stopped." << std::endl;
            }
            kopsik_time_entry_view_item_clear(te);
            return Poco::Util::Application::EXIT_OK;
        }

        if ("list" == args[0]) {
            KopsikTimeEntryViewItemList *list =
                kopsik_time_entry_view_item_list_init();
            if (KOPSIK_API_SUCCESS != kopsik_time_entry_view_items(
                    ctx, err, ERRLEN, list)) {
                std::cerr << err << std::endl;
                kopsik_time_entry_view_item_list_clear(list);
                return Poco::Util::Application::EXIT_SOFTWARE;
            }
            for (unsigned int i = 0; i < list->Length; i++) {
                KopsikTimeEntryViewItem *item = list->ViewItems[i];
                std::cout << KopsikTimeEntryViewItemToString(item) << std::endl;
            }
            std::cout << "Got " << list->Length << " time entry view items."
                << std::endl;
            kopsik_time_entry_view_item_list_clear(list);
            return Poco::Util::Application::EXIT_OK;
        }

        if ("listen" == args[0]) {
            std::cout << "Listening to websocket.. " << std::endl;
            kopsik_set_change_callback(ctx, on_view_item_change);
            if (KOPSIK_API_SUCCESS != kopsik_websocket_start(ctx, err, ERRLEN)) {
                std::cerr << "Error starting websocket: "
                    << err << std::endl;
                return Poco::Util::Application::EXIT_SOFTWARE;
            }
            while (true) {
                Poco::Thread::sleep(1000);
            }
            if (KOPSIK_API_SUCCESS != kopsik_websocket_stop(ctx, err, ERRLEN)) {
                std::cerr << "Error stopping websocket: "
                    << err << std::endl;
                return Poco::Util::Application::EXIT_SOFTWARE;
            }
            return Poco::Util::Application::EXIT_OK;
        }

        if ("continue" == args[0]) {
            KopsikTimeEntryViewItemList *list =
                kopsik_time_entry_view_item_list_init();

            if (KOPSIK_API_SUCCESS != kopsik_time_entry_view_items(
                    ctx, err, ERRLEN, list)) {
                std::cerr << err << std::endl;
                kopsik_time_entry_view_item_list_clear(list);
                return Poco::Util::Application::EXIT_SOFTWARE;
            }

            if (!list->Length) {
                std::cout << "No time entry found to continue." << std::endl;
                kopsik_time_entry_view_item_list_clear(list);
                return Poco::Util::Application::EXIT_OK;
            }

            KopsikTimeEntryViewItem *te = kopsik_time_entry_view_item_init();
            if (KOPSIK_API_SUCCESS != kopsik_continue(
                    ctx, err, ERRLEN, list->ViewItems[0]->GUID, te)) {
                std::cerr << err << std::endl;
                kopsik_time_entry_view_item_list_clear(list);
                kopsik_time_entry_view_item_clear(te);
                return Poco::Util::Application::EXIT_SOFTWARE;
            }

            if (KOPSIK_API_SUCCESS != kopsik_push(ctx, err, ERRLEN)) {
                std::cerr << err << std::endl;
            }

            if (te->Description) {
                std::cout << "Started: " << te->Description << std::endl;
            } else {
                std::cout << "Started." << std::endl;
            }

            kopsik_time_entry_view_item_list_clear(list);
            kopsik_time_entry_view_item_clear(te);
            return Poco::Util::Application::EXIT_OK;
        }

        usage();
        return Poco::Util::Application::EXIT_USAGE;
    }
}  // namespace command_line_client
<commit_msg>rename model change event in cmd line app<commit_after>// Copyright 2013 Tanel Lebedev

#include "./main.h"

#include <sstream>

#include "Poco/Message.h"
#include "Poco/Util/Application.h"

#define ERRLEN 1024

namespace command_line_client {

    void Main::usage() {
        std::cout << "Recognized commands are: "
            "sync, start, stop, status, pushable, list, continue, listen"
            << std::endl;
    }

    void Main::defineOptions(Poco::Util::OptionSet& options) {
        Poco::Util::Application::defineOptions(options);
        options.addOption(Poco::Util::Option(
            "verbose", "v", "verbose logging, to the console"));
    }

    std::string KopsikModelChangeToString(
            KopsikModelChange &change) {
        std::stringstream ss;
        ss  << "model_type=" << change.ModelType
            << ", change_type=" << change.ChangeType
            << ", model_id=" << change.ModelID
            << ", GUID=" << change.GUID;
        return ss.str();
    }

    std::string KopsikTimeEntryViewItemToString(
            KopsikTimeEntryViewItem *item) {
        std::stringstream ss;
        ss << "description: " << item->Description;
        if (item->Project) {
            ss << " project: " << item->Project;
        }
        if (item->Duration) {
            ss << " duration: " << item->Duration;
        }
        return ss.str();
    }

    void on_model_change(kopsik_api_result result,
            char *err_string,
            int unsigned err_len,
            KopsikModelChange *change) {
        if (KOPSIK_API_SUCCESS != result) {
            std::string err("");
            err.append(err_string, err_len);
            std::cerr << "on_model_change error! "
                << err << std::endl;
            free(err_string);
            return;
        }
        std::cout << "on_view_item_change "
            << KopsikModelChangeToString(*change)
            << std::endl;
    }

    int Main::main(const std::vector<std::string>& args) {
        if (args.empty()) {
            usage();
            return Poco::Util::Application::EXIT_USAGE;
        }

        char* apiToken = getenv("TOGGL_API_TOKEN");
        if (!apiToken) {
            std::cerr << "Please set TOGGL_API_TOKEN in environment" <<
                std::endl;
            return Poco::Util::Application::EXIT_USAGE;
        }

        kopsik_set_db_path(ctx, "kopsik.db");
        kopsik_set_log_path(ctx, "kopsik.log");

        Poco::ErrorHandler::set(this);

        // Start session in lib
        char err[ERRLEN];
        std::fill(err, err + ERRLEN, 0);
        if (KOPSIK_API_SUCCESS != kopsik_set_api_token(
                ctx, err, ERRLEN, apiToken)) {
            std::cerr << err << std::endl;
            return Poco::Util::Application::EXIT_SOFTWARE;
        }

        // Load user that is referenced by the session
        KopsikUser *user = kopsik_user_init();
        if (KOPSIK_API_SUCCESS != kopsik_current_user(
                ctx, err, ERRLEN, user)) {
            std::cerr << err << std::endl;
            return Poco::Util::Application::EXIT_SOFTWARE;
        }
        kopsik_user_clear(user);

        if ("sync" == args[0]) {
            if (KOPSIK_API_SUCCESS != kopsik_sync(ctx, err, ERRLEN, 1)) {
                std::cerr << err << std::endl;
                return Poco::Util::Application::EXIT_SOFTWARE;
            }
            std::cout << "Synced." << std::endl;
            return Poco::Util::Application::EXIT_OK;
        }

        if ("status" == args[0]) {
            KopsikTimeEntryViewItem *te = kopsik_time_entry_view_item_init();
            int found(0);
            if (KOPSIK_API_SUCCESS != kopsik_running_time_entry_view_item(
                    ctx, err, ERRLEN, te, &found)) {
                std::cerr << err << std::endl;
                kopsik_time_entry_view_item_clear(te);
                return Poco::Util::Application::EXIT_SOFTWARE;
            }
            if (found) {
                std::cout << "Tracking: " << te->Description << std::endl;
            } else {
                std::cout << "Not tracking." << std::endl;
            }
            kopsik_time_entry_view_item_clear(te);
            return Poco::Util::Application::EXIT_OK;
        }

        if ("pushable" == args[0]) {
            KopsikPushableModelStats stats;
            if (KOPSIK_API_SUCCESS != kopsik_pushable_models(
                    ctx, err, ERRLEN, &stats)) {
                std::cerr << err << std::endl;
                return Poco::Util::Application::EXIT_SOFTWARE;
            }
            std::cout << stats.TimeEntries << " pushable time entries." << std::endl;
            return Poco::Util::Application::EXIT_OK;
        }

        if ("start" == args[0]) {
            KopsikTimeEntryViewItem *te = kopsik_time_entry_view_item_init();
            if (KOPSIK_API_SUCCESS != kopsik_start(
                    ctx, err, ERRLEN, "New time entry", te)) {
                std::cerr << err << std::endl;
                kopsik_time_entry_view_item_clear(te);
                return Poco::Util::Application::EXIT_SOFTWARE;
            }
            if (KOPSIK_API_SUCCESS != kopsik_push(ctx, err, ERRLEN)) {
                std::cerr << err << std::endl;
            }
            if (te->Description) {
                std::cout << "Started: " << te->Description << std::endl;
            } else {
                std::cout << "Started." << std::endl;
            }
            kopsik_time_entry_view_item_clear(te);
            return Poco::Util::Application::EXIT_OK;
        }

        if ("stop" == args[0]) {
            KopsikTimeEntryViewItem *te = kopsik_time_entry_view_item_init();
            if (KOPSIK_API_SUCCESS != kopsik_stop(
                    ctx, err, ERRLEN, te)) {
                std::cerr << err << std::endl;
                kopsik_time_entry_view_item_clear(te);
                return Poco::Util::Application::EXIT_SOFTWARE;
            }
            if (KOPSIK_API_SUCCESS != kopsik_push(ctx, err, ERRLEN)) {
                std::cerr << err << std::endl;
            }
            if (te->Description) {
                std::cout << "Stopped: " << te->Description << std::endl;
            } else {
                std::cout << "Stopped." << std::endl;
            }
            kopsik_time_entry_view_item_clear(te);
            return Poco::Util::Application::EXIT_OK;
        }

        if ("list" == args[0]) {
            KopsikTimeEntryViewItemList *list =
                kopsik_time_entry_view_item_list_init();
            if (KOPSIK_API_SUCCESS != kopsik_time_entry_view_items(
                    ctx, err, ERRLEN, list)) {
                std::cerr << err << std::endl;
                kopsik_time_entry_view_item_list_clear(list);
                return Poco::Util::Application::EXIT_SOFTWARE;
            }
            for (unsigned int i = 0; i < list->Length; i++) {
                KopsikTimeEntryViewItem *item = list->ViewItems[i];
                std::cout << KopsikTimeEntryViewItemToString(item) << std::endl;
            }
            std::cout << "Got " << list->Length << " time entry view items."
                << std::endl;
            kopsik_time_entry_view_item_list_clear(list);
            return Poco::Util::Application::EXIT_OK;
        }

        if ("listen" == args[0]) {
            std::cout << "Listening to websocket.. " << std::endl;
            kopsik_set_change_callback(ctx, on_model_change);
            if (KOPSIK_API_SUCCESS != kopsik_websocket_start(ctx, err, ERRLEN)) {
                std::cerr << "Error starting websocket: "
                    << err << std::endl;
                return Poco::Util::Application::EXIT_SOFTWARE;
            }
            while (true) {
                Poco::Thread::sleep(1000);
            }
            if (KOPSIK_API_SUCCESS != kopsik_websocket_stop(ctx, err, ERRLEN)) {
                std::cerr << "Error stopping websocket: "
                    << err << std::endl;
                return Poco::Util::Application::EXIT_SOFTWARE;
            }
            return Poco::Util::Application::EXIT_OK;
        }

        if ("continue" == args[0]) {
            KopsikTimeEntryViewItemList *list =
                kopsik_time_entry_view_item_list_init();

            if (KOPSIK_API_SUCCESS != kopsik_time_entry_view_items(
                    ctx, err, ERRLEN, list)) {
                std::cerr << err << std::endl;
                kopsik_time_entry_view_item_list_clear(list);
                return Poco::Util::Application::EXIT_SOFTWARE;
            }

            if (!list->Length) {
                std::cout << "No time entry found to continue." << std::endl;
                kopsik_time_entry_view_item_list_clear(list);
                return Poco::Util::Application::EXIT_OK;
            }

            KopsikTimeEntryViewItem *te = kopsik_time_entry_view_item_init();
            if (KOPSIK_API_SUCCESS != kopsik_continue(
                    ctx, err, ERRLEN, list->ViewItems[0]->GUID, te)) {
                std::cerr << err << std::endl;
                kopsik_time_entry_view_item_list_clear(list);
                kopsik_time_entry_view_item_clear(te);
                return Poco::Util::Application::EXIT_SOFTWARE;
            }

            if (KOPSIK_API_SUCCESS != kopsik_push(ctx, err, ERRLEN)) {
                std::cerr << err << std::endl;
            }

            if (te->Description) {
                std::cout << "Started: " << te->Description << std::endl;
            } else {
                std::cout << "Started." << std::endl;
            }

            kopsik_time_entry_view_item_list_clear(list);
            kopsik_time_entry_view_item_clear(te);
            return Poco::Util::Application::EXIT_OK;
        }

        usage();
        return Poco::Util::Application::EXIT_USAGE;
    }
}  // namespace command_line_client
<|endoftext|>


<commit_before>
#include <iostream>

#include <glow/Buffer.h>
#include <glow/Error.h>

namespace glow
{

Buffer::Buffer()
: Object(genBuffer())
, _target(0)
{
}

Buffer::Buffer(GLenum target)
: Object(genBuffer())
, _target(target)
{
}

Buffer::Buffer(GLuint id, GLenum target, bool ownsGLObject)
: Object(id, ownsGLObject)
, _target(target)
{

}

GLuint Buffer::genBuffer()
{
	GLuint id = 0;

	glGenBuffers(1, &id);
	CheckGLError();

	return id;
}

Buffer::~Buffer()
{
	if (m_id)
	{
		glDeleteBuffers(1, &m_id);
		CheckGLError();
	}
}

void Buffer::bind()
{
	glBindBuffer(_target, m_id);
	CheckGLError();
}

void Buffer::bind(GLenum target)
{
	_target = target;
	bind();
}

void Buffer::unbind()
{
	glBindBuffer(_target, 0);
	CheckGLError();
}

void* Buffer::map(GLenum access)
{
	bind();

	void* result = glMapBuffer(_target, access);
	CheckGLError();
	return result;
}

void* Buffer::map(GLenum target, GLenum access)
{
	bind(target);

	void* result = glMapBuffer(target, access);
	CheckGLError();
	return result;
}

void Buffer::unmap()
{
	glUnmapBuffer(_target);
	CheckGLError();
}

void Buffer::setData(const AbstractArray& data, GLenum usage)
{
	setData(data.rawSize(), data.rawData(), usage);
}

void Buffer::setData(GLsizei size, const GLvoid* data, GLenum usage)
{
	bind();
	glBufferData(_target, size, data, usage);
	CheckGLError();
}

void Buffer::drawArrays(GLenum mode, GLint first, GLsizei count)
{
	bind();
	glDrawArrays(mode, first, count);
	CheckGLError();
}

void Buffer::drawElements(GLenum mode, GLsizei count, GLenum type, const GLvoid* indices)
{
	bind();
	glDrawElements(mode, count, type, indices);
	CheckGLError();
}

void Buffer::bindBase(GLenum target, GLuint index)
{
	glBindBufferBase(target, index, m_id);
	CheckGLError();
}

void Buffer::bindRange(GLenum target, GLuint index, GLintptr offset, GLsizeiptr size)
{
	glBindBufferRange(target, index, m_id, offset, size);
	CheckGLError();
}

} // namespace glow
<commit_msg>ref #15 beautification<commit_after>
#include <iostream>

#include <glow/Buffer.h>
#include <glow/Error.h>

namespace glow
{

Buffer::Buffer()
: Object(genBuffer())
, _target(0)
{
}

Buffer::Buffer(GLenum target)
: Object(genBuffer())
, _target(target)
{
}

Buffer::Buffer(GLuint id, GLenum target, bool ownsGLObject)
: Object(id, ownsGLObject)
, _target(target)
{
}

GLuint Buffer::genBuffer()
{
	GLuint id = 0;

	glGenBuffers(1, &id);
	CheckGLError();

	return id;
}

Buffer::~Buffer()
{
	if (m_id)
	{
		glDeleteBuffers(1, &m_id);
		CheckGLError();
	}
}

void Buffer::bind()
{
	glBindBuffer(_target, m_id);
	CheckGLError();
}

void Buffer::bind(GLenum target)
{
	_target = target;
	bind();
}

void Buffer::unbind()
{
	glBindBuffer(_target, 0);
	CheckGLError();
}

void* Buffer::map(GLenum access)
{
	bind();

	void* result = glMapBuffer(_target, access);
	CheckGLError();
	return result;
}

void* Buffer::map(GLenum target, GLenum access)
{
	bind(target);

	void* result = glMapBuffer(target, access);
	CheckGLError();
	return result;
}

void Buffer::unmap()
{
	glUnmapBuffer(_target);
	CheckGLError();
}

void Buffer::setData(const AbstractArray& data, GLenum usage)
{
	setData(data.rawSize(), data.rawData(), usage);
}

void Buffer::setData(GLsizei size, const GLvoid* data, GLenum usage)
{
	bind();
	glBufferData(_target, size, data, usage);
	CheckGLError();
}

void Buffer::drawArrays(GLenum mode, GLint first, GLsizei count)
{
	bind();
	glDrawArrays(mode, first, count);
	CheckGLError();
}

void Buffer::drawElements(GLenum mode, GLsizei count, GLenum type, const GLvoid* indices)
{
	bind();
	glDrawElements(mode, count, type, indices);
	CheckGLError();
}

void Buffer::bindBase(GLenum target, GLuint index)
{
	glBindBufferBase(target, index, m_id);
	CheckGLError();
}

void Buffer::bindRange(GLenum target, GLuint index, GLintptr offset, GLsizeiptr size)
{
	glBindBufferRange(target, index, m_id, offset, size);
	CheckGLError();
}

} // namespace glow
<|endoftext|>


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

#include <unistd.h>
#include <stdio.h>
#include <gtest/gtest.h>
#include "configtest.hpp"

#include "../inc/config.hpp"

void ConfigTest::SetUp()
{
	config_file = "test.conf";
	config_path = "./";
}

void ConfigTest::TearDown()
{
	// delete file if it exists
	std::string file = config_path + config_file;
	if (access(file.c_str(), 0) == F_OK) {
		int status = remove(file.c_str());
		if (status != 0) {
			FAIL() << "Cannot delete test configuration file";
		}
	}
}

TEST_F(ConfigTest, ConstructorCreatesValidConfigurationObject)
{
	// when
	jippi::Config *conf = new jippi::Config(config_file, config_path);

	// then
	EXPECT_EQ(config_path + config_file, conf->get_file());

	// cleanup
 	delete conf;
}

TEST_F(ConfigTest, StorePropertySavesValue)
{
	// given
	const std::string value = "test_value";
	const std::string group = "test_group";
	const std::string key = "test_property";

	// when
	jippi::Config *conf = new jippi::Config(config_file, config_path);
	conf->store_property(group, key, value);
	conf->writeConfiguration();

	conf->readConfiguration();
	std::string config_value = conf->get_property(group, key);

	// then
	EXPECT_EQ(value, config_value);

	// cleanup
	delete conf;
}<commit_msg>Rename configtest.h and move it to the 'inc' directory<commit_after>/*
 * Copyright 2014 Kamil Michalak <kmichalak8@gmail.com>
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *
 */

#include <unistd.h>
#include <stdio.h>
#include <gtest/gtest.h>
#include "inc/configtest.hpp"

#include "../inc/config.hpp"

void ConfigTest::SetUp()
{
	config_file = "test.conf";
	config_path = "./";
}

void ConfigTest::TearDown()
{
	// delete file if it exists
	std::string file = config_path + config_file;
	if (access(file.c_str(), 0) == F_OK) {
		int status = remove(file.c_str());
		if (status != 0) {
			FAIL() << "Cannot delete test configuration file";
		}
	}
}

TEST_F(ConfigTest, ConstructorCreatesValidConfigurationObject)
{
	// when
	jippi::Config *conf = new jippi::Config(config_file, config_path);

	// then
	EXPECT_EQ(config_path + config_file, conf->get_file());

	// cleanup
 	delete conf;
}

TEST_F(ConfigTest, StorePropertySavesValue)
{
	// given
	const std::string value = "test_value";
	const std::string group = "test_group";
	const std::string key = "test_property";

	// when
	jippi::Config *conf = new jippi::Config(config_file, config_path);
	conf->store_property(group, key, value);
	conf->writeConfiguration();

	conf->readConfiguration();
	std::string config_value = conf->get_property(group, key);

	// then
	EXPECT_EQ(value, config_value);

	// cleanup
	delete conf;
}<|endoftext|>


<commit_before>
#include <cassert>

#include <QDebug>
#include <QApplication>
#include <QBasicTimer>
#include <QResizeEvent>

#include "AbstractPainter.h"
#include "AdaptiveGrid.h"
#include "FileAssociatedShader.h"
#include "Camera.h"
#include "Navigation.h"
#include "NavigationMath.h"
#include "Timer.h"
#include "CyclicTime.h"
#include "Canvas.h"

Canvas::Canvas(
    const QSurfaceFormat & format
,   QScreen * screen)
: QWindow(screen)
, m_context(new QOpenGLContext)
, m_painter(nullptr)
, m_camera(new Camera())
, m_navigation(new Navigation(*m_camera))
, m_swapInterval(VerticalSyncronization)
, m_repaintTimer(new QBasicTimer())
, m_continuousRepaint(false)
, m_fpsTimer(nullptr)
, m_time(new CyclicTime(0.0L, 60.0)) // this is one day in 60 seconds (1d/1h)
, m_swapts(0.0)
, m_swaps(0)
, m_update(false)
{
    setSurfaceType(OpenGLSurface);

    create();

    m_camera->setFovy(40.0);
    m_navigation->reset();

    initializeGL(format);
}

Canvas::~Canvas()
{
}

QSurfaceFormat Canvas::format() const
{
    if (!m_context)
        return QSurfaceFormat();

    return m_context->format();
}

void Canvas::setContinuousRepaint(
    bool enable
,   int msec)
{
    if (m_continuousRepaint)
        m_repaintTimer->stop();

	m_continuousRepaint = enable;

    if (m_continuousRepaint)
        m_repaintTimer->start(msec, this);
}

bool Canvas::continuousRepaint() const
{
	return m_continuousRepaint;
}

const QString Canvas::querys(const GLenum penum)
{
    const QString result = reinterpret_cast<const char*>(glGetString(penum));
    //glError();

    return result;
}

const GLint Canvas::queryi(const GLenum penum)
{
    GLint result;
    glGetIntegerv(penum, &result);

    return result;
}

void Canvas::initializeGL(const QSurfaceFormat & format)
{
    m_context->setFormat(format);
    m_context->create();

    m_context->makeCurrent(this);
    if (!initializeOpenGLFunctions())
    {
        qCritical() << "Initializing OpenGL failed.";
        return;
    }

    // print some hardware information

    qDebug();
    qDebug().nospace() << "GPU: "
        << qPrintable(querys(GL_RENDERER)) << " ("
        << qPrintable(querys(GL_VENDOR)) << ", "
        << qPrintable(querys(GL_VERSION)) << ")";
    qDebug().nospace() << "GL Version: "
        << qPrintable(QString::number(queryi(GL_MAJOR_VERSION))) << "."
        << qPrintable(QString::number(queryi(GL_MINOR_VERSION))) << " "
        << (queryi(GL_CONTEXT_CORE_PROFILE_BIT) ? "Core" : "Compatibility");
    qDebug();

    verifyExtensions(); // false if no painter ...

    m_grid.reset(new AdaptiveGrid(*this));
    m_grid->setNearFar(m_camera->zNear(), m_camera->zFar());

    connect(m_camera.data(), &Camera::changed, this, &Canvas::cameraChanged);

    m_context->doneCurrent();

    m_time->setf(0.0);
    m_time->start();
}

void Canvas::resizeEvent(QResizeEvent * event)
{
    if (!m_painter)
        return;

    m_camera->setViewport(event->size());

    m_context->makeCurrent(this);

    m_painter->resize(event->size().width(), event->size().height());
    m_grid->update(m_camera->eye(), m_camera->viewProjection());

    m_context->doneCurrent();

    if (isExposed() && Hidden != visibility())
        paintGL();
}

void Canvas::paintGL()
{
    if (!m_painter || !isExposed() || Hidden == visibility())
        return;

    m_context->makeCurrent(this);
    auto programsWithInvalidatedUniforms(FileAssociatedShader::process()); // recompile file associated shaders if required

    if (m_update)
    {
        m_painter->update();
        m_grid->update(m_camera->eye(), m_camera->viewProjection());

        m_update = false;
    }
    else
        m_painter->update(programsWithInvalidatedUniforms);

	m_painter->paint(m_time->getf(true));
    m_grid->draw(*this);

    m_context->swapBuffers(this);
    m_context->doneCurrent();

    emit timeUpdate(m_time->getf());

    if (!m_fpsTimer)
    {
        m_fpsTimer.reset(new Timer(true, false));
        m_swapts = 0.0;
    }
    else
        m_fpsTimer->update();

    ++m_swaps;

    if (m_fpsTimer->elapsed() - m_swapts >= 1e+9)
    {
        const float fps = 1e+9f * static_cast<float>(static_cast<long double>
            (m_swaps) / (m_fpsTimer->elapsed() - m_swapts));

        emit fpsUpdate(fps);

        m_swapts = m_fpsTimer->elapsed();
        m_swaps = 0;
    }
}

void Canvas::cameraChanged()
{
    m_update = true;
}

void Canvas::timerEvent(QTimerEvent * event)
{
    assert(m_repaintTimer);

    if(event->timerId() != m_repaintTimer->timerId())
        return;

    paintGL();
}

void Canvas::assignPainter(AbstractPainter * painter)
{
    if (m_painter == painter)
        return;

    m_painter = painter;
    if (!m_painter)
        return;

    m_context->makeCurrent(this);

    m_painter->initialize();
    m_painter->setCamera(m_camera.data());

    verifyExtensions();

    m_context->doneCurrent();

    m_navigation->setCoordinateProvider(m_painter);
}

bool Canvas::verifyExtensions() const
{
    if (!m_painter)
        return false;

    if (!m_context->isValid())
    {
        qWarning("Extensions cannot be verified due to invalid context.");
        return false;
    }

    QStringList unsupported;

    const QStringList & extensions(m_painter->extensions());
    foreach(const QString & extension, extensions)
    if (!m_context->hasExtension(qPrintable(extension)))
        unsupported << extension;

    if (unsupported.isEmpty())
        return true;

    if (unsupported.size() > 1)
        qWarning("The following mandatory OpenGL extensions are not supported:");
    else
        qWarning("The following mandatory OpenGL extension is not supported:");

    foreach(const QString & extension, unsupported)
        qWarning() << extension;

    qWarning("");

    return false;
}

void Canvas::setSwapInterval(SwapInterval swapInterval)
{
    m_context->makeCurrent(this);

    bool result(false);
    m_swapInterval = swapInterval;

#ifdef WIN32

    // ToDo: C++11 - type aliases
    typedef bool(WINAPI * SWAPINTERVALEXTPROC) (int);
    static SWAPINTERVALEXTPROC wglSwapIntervalEXT = nullptr;

    if (!wglSwapIntervalEXT)
        wglSwapIntervalEXT = reinterpret_cast<SWAPINTERVALEXTPROC>(m_context->getProcAddress("wglSwapIntervalEXT"));
    if (wglSwapIntervalEXT)
        result = wglSwapIntervalEXT(swapInterval);

#elif __APPLE__

    qWarning("ToDo: Setting swap interval is currently not implemented for __APPLE__");

#else
    // ToDo: C++11 - type aliases
    typedef int(APIENTRY * SWAPINTERVALEXTPROC) (int);
    static SWAPINTERVALEXTPROC glXSwapIntervalSGI = nullptr;

    if (!glXSwapIntervalSGI)
        glXSwapIntervalSGI = reinterpret_cast<SWAPINTERVALEXTPROC>(m_context->getProcAddress("glXSwapIntervalSGI"));
    if (glXSwapIntervalSGI)
        result = glXSwapIntervalSGI(swapInterval);

#endif

    if (!result)
        qWarning("Setting swap interval to %s failed."
            , qPrintable(swapIntervalToString(swapInterval)));
    else
        qDebug("Setting swap interval to %s."
            , qPrintable(swapIntervalToString(swapInterval)));

    m_context->doneCurrent();
}

void Canvas::toggleSwapInterval()
{
    switch (m_swapInterval)
    {
    case NoVerticalSyncronization:
        setSwapInterval(VerticalSyncronization);
        break;
    case VerticalSyncronization:
        setSwapInterval(AdaptiveVerticalSyncronization);
        break;
    case AdaptiveVerticalSyncronization:
        setSwapInterval(NoVerticalSyncronization);
        break;
    }
}

const QString Canvas::swapIntervalToString(SwapInterval swapInterval)
{
    switch (swapInterval)
    {
    case NoVerticalSyncronization:
        return QString("NoVerticalSyncronization");
    case VerticalSyncronization:
        return QString("VerticalSyncronization");
    case AdaptiveVerticalSyncronization:
        return QString("AdaptiveVerticalSyncronization");
    default:
        return QString();
    }
}

void Canvas::keyPressEvent(QKeyEvent * event)
{
    if (!m_navigation)
        return;

    m_navigation->keyPressEvent(event);

	// forward event to painter for exercise mode switching
	m_painter->keyPressEvent(event);
}
void Canvas::keyReleaseEvent(QKeyEvent * event)
{
    if (!m_navigation)
        return;

    m_navigation->keyReleaseEvent(event);
}

void Canvas::mouseMoveEvent(QMouseEvent * event)
{
    if (!m_navigation)
        return;

    m_context->makeCurrent(this);
    m_navigation->mouseMoveEvent(event);

    emit mouseUpdate(event->pos());
    if (m_painter)
    {
        if (NavigationMath::validDepth(m_painter->depthAt(event->pos())))
            emit objUpdate(m_painter->objAt(event->pos()));
        else
            emit objUpdate(QVector3D());
    }
    m_context->doneCurrent();
}

void Canvas::mousePressEvent(QMouseEvent * event)
{
    if (!m_navigation)
        return;

    m_context->makeCurrent(this);
    m_navigation->mousePressEvent(event);
    m_context->doneCurrent();
}

void Canvas::mouseReleaseEvent(QMouseEvent * event)
{
    if (!m_navigation)
        return;

    m_context->makeCurrent(this);
    m_navigation->mouseReleaseEvent(event);
    m_context->doneCurrent();
}

void Canvas::mouseDoubleClickEvent(QMouseEvent * event)
{
    if (!m_navigation)
        return;

    m_context->makeCurrent(this);
    m_navigation->mouseDoubleClickEvent(event);
    m_context->doneCurrent();
}

void Canvas::wheelEvent(QWheelEvent * event)
{
    if (!m_navigation)
        return;

    m_context->makeCurrent(this);
    m_navigation->wheelEvent(event);
    m_context->doneCurrent();
}
<commit_msg>additional error message<commit_after>
#include <cassert>

#include <QDebug>
#include <QApplication>
#include <QBasicTimer>
#include <QResizeEvent>

#include "AbstractPainter.h"
#include "AdaptiveGrid.h"
#include "FileAssociatedShader.h"
#include "Camera.h"
#include "Navigation.h"
#include "NavigationMath.h"
#include "Timer.h"
#include "CyclicTime.h"
#include "Canvas.h"

Canvas::Canvas(
    const QSurfaceFormat & format
,   QScreen * screen)
: QWindow(screen)
, m_context(new QOpenGLContext)
, m_painter(nullptr)
, m_camera(new Camera())
, m_navigation(new Navigation(*m_camera))
, m_swapInterval(VerticalSyncronization)
, m_repaintTimer(new QBasicTimer())
, m_continuousRepaint(false)
, m_fpsTimer(nullptr)
, m_time(new CyclicTime(0.0L, 60.0)) // this is one day in 60 seconds (1d/1h)
, m_swapts(0.0)
, m_swaps(0)
, m_update(false)
{
    setSurfaceType(OpenGLSurface);

    create();

    m_camera->setFovy(40.0);
    m_navigation->reset();

    initializeGL(format);
}

Canvas::~Canvas()
{
}

QSurfaceFormat Canvas::format() const
{
    if (!m_context)
        return QSurfaceFormat();

    return m_context->format();
}

void Canvas::setContinuousRepaint(
    bool enable
,   int msec)
{
    if (m_continuousRepaint)
        m_repaintTimer->stop();

	m_continuousRepaint = enable;

    if (m_continuousRepaint)
        m_repaintTimer->start(msec, this);
}

bool Canvas::continuousRepaint() const
{
	return m_continuousRepaint;
}

const QString Canvas::querys(const GLenum penum)
{
    const QString result = reinterpret_cast<const char*>(glGetString(penum));
    //glError();

    return result;
}

const GLint Canvas::queryi(const GLenum penum)
{
    GLint result;
    glGetIntegerv(penum, &result);

    return result;
}

void Canvas::initializeGL(const QSurfaceFormat & format)
{
    m_context->setFormat(format);
    if (!m_context->create())
	{
		qCritical() << "Errors during creation of OpenGL context.";
		return;
	}

    m_context->makeCurrent(this);
    if (!initializeOpenGLFunctions())
    {
        qCritical() << "Initializing OpenGL failed.";
        return;
    }

    // print some hardware information

    qDebug();
    qDebug().nospace() << "GPU: "
        << qPrintable(querys(GL_RENDERER)) << " ("
        << qPrintable(querys(GL_VENDOR)) << ", "
        << qPrintable(querys(GL_VERSION)) << ")";
    qDebug().nospace() << "GL Version: "
        << qPrintable(QString::number(queryi(GL_MAJOR_VERSION))) << "."
        << qPrintable(QString::number(queryi(GL_MINOR_VERSION))) << " "
        << (queryi(GL_CONTEXT_CORE_PROFILE_BIT) ? "Core" : "Compatibility");
    qDebug();

    verifyExtensions(); // false if no painter ...

    m_grid.reset(new AdaptiveGrid(*this));
    m_grid->setNearFar(m_camera->zNear(), m_camera->zFar());

    connect(m_camera.data(), &Camera::changed, this, &Canvas::cameraChanged);

    m_context->doneCurrent();

    m_time->setf(0.0);
    m_time->start();
}

void Canvas::resizeEvent(QResizeEvent * event)
{
    if (!m_painter)
        return;

    m_camera->setViewport(event->size());

    m_context->makeCurrent(this);

    m_painter->resize(event->size().width(), event->size().height());
    m_grid->update(m_camera->eye(), m_camera->viewProjection());

    m_context->doneCurrent();

    if (isExposed() && Hidden != visibility())
        paintGL();
}

void Canvas::paintGL()
{
    if (!m_painter || !isExposed() || Hidden == visibility())
        return;

    m_context->makeCurrent(this);
    auto programsWithInvalidatedUniforms(FileAssociatedShader::process()); // recompile file associated shaders if required

    if (m_update)
    {
        m_painter->update();
        m_grid->update(m_camera->eye(), m_camera->viewProjection());

        m_update = false;
    }
    else
        m_painter->update(programsWithInvalidatedUniforms);

	m_painter->paint(m_time->getf(true));
    m_grid->draw(*this);

    m_context->swapBuffers(this);
    m_context->doneCurrent();

    emit timeUpdate(m_time->getf());

    if (!m_fpsTimer)
    {
        m_fpsTimer.reset(new Timer(true, false));
        m_swapts = 0.0;
    }
    else
        m_fpsTimer->update();

    ++m_swaps;

    if (m_fpsTimer->elapsed() - m_swapts >= 1e+9)
    {
        const float fps = 1e+9f * static_cast<float>(static_cast<long double>
            (m_swaps) / (m_fpsTimer->elapsed() - m_swapts));

        emit fpsUpdate(fps);

        m_swapts = m_fpsTimer->elapsed();
        m_swaps = 0;
    }
}

void Canvas::cameraChanged()
{
    m_update = true;
}

void Canvas::timerEvent(QTimerEvent * event)
{
    assert(m_repaintTimer);

    if(event->timerId() != m_repaintTimer->timerId())
        return;

    paintGL();
}

void Canvas::assignPainter(AbstractPainter * painter)
{
    if (m_painter == painter)
        return;

    m_painter = painter;
    if (!m_painter)
        return;

    m_context->makeCurrent(this);

    m_painter->initialize();
    m_painter->setCamera(m_camera.data());

    verifyExtensions();

    m_context->doneCurrent();

    m_navigation->setCoordinateProvider(m_painter);
}

bool Canvas::verifyExtensions() const
{
    if (!m_painter)
        return false;

    if (!m_context->isValid())
    {
        qWarning("Extensions cannot be verified due to invalid context.");
        return false;
    }

    QStringList unsupported;

    const QStringList & extensions(m_painter->extensions());
    foreach(const QString & extension, extensions)
    if (!m_context->hasExtension(qPrintable(extension)))
        unsupported << extension;

    if (unsupported.isEmpty())
        return true;

    if (unsupported.size() > 1)
        qWarning("The following mandatory OpenGL extensions are not supported:");
    else
        qWarning("The following mandatory OpenGL extension is not supported:");

    foreach(const QString & extension, unsupported)
        qWarning() << extension;

    qWarning("");

    return false;
}

void Canvas::setSwapInterval(SwapInterval swapInterval)
{
    m_context->makeCurrent(this);

    bool result(false);
    m_swapInterval = swapInterval;

#ifdef WIN32

    // ToDo: C++11 - type aliases
    typedef bool(WINAPI * SWAPINTERVALEXTPROC) (int);
    static SWAPINTERVALEXTPROC wglSwapIntervalEXT = nullptr;

    if (!wglSwapIntervalEXT)
        wglSwapIntervalEXT = reinterpret_cast<SWAPINTERVALEXTPROC>(m_context->getProcAddress("wglSwapIntervalEXT"));
    if (wglSwapIntervalEXT)
        result = wglSwapIntervalEXT(swapInterval);

#elif __APPLE__

    qWarning("ToDo: Setting swap interval is currently not implemented for __APPLE__");

#else
    // ToDo: C++11 - type aliases
    typedef int(APIENTRY * SWAPINTERVALEXTPROC) (int);
    static SWAPINTERVALEXTPROC glXSwapIntervalSGI = nullptr;

    if (!glXSwapIntervalSGI)
        glXSwapIntervalSGI = reinterpret_cast<SWAPINTERVALEXTPROC>(m_context->getProcAddress("glXSwapIntervalSGI"));
    if (glXSwapIntervalSGI)
        result = glXSwapIntervalSGI(swapInterval);

#endif

    if (!result)
        qWarning("Setting swap interval to %s failed."
            , qPrintable(swapIntervalToString(swapInterval)));
    else
        qDebug("Setting swap interval to %s."
            , qPrintable(swapIntervalToString(swapInterval)));

    m_context->doneCurrent();
}

void Canvas::toggleSwapInterval()
{
    switch (m_swapInterval)
    {
    case NoVerticalSyncronization:
        setSwapInterval(VerticalSyncronization);
        break;
    case VerticalSyncronization:
        setSwapInterval(AdaptiveVerticalSyncronization);
        break;
    case AdaptiveVerticalSyncronization:
        setSwapInterval(NoVerticalSyncronization);
        break;
    }
}

const QString Canvas::swapIntervalToString(SwapInterval swapInterval)
{
    switch (swapInterval)
    {
    case NoVerticalSyncronization:
        return QString("NoVerticalSyncronization");
    case VerticalSyncronization:
        return QString("VerticalSyncronization");
    case AdaptiveVerticalSyncronization:
        return QString("AdaptiveVerticalSyncronization");
    default:
        return QString();
    }
}

void Canvas::keyPressEvent(QKeyEvent * event)
{
    if (!m_navigation)
        return;

    m_navigation->keyPressEvent(event);

	// forward event to painter for exercise mode switching
	m_painter->keyPressEvent(event);
}
void Canvas::keyReleaseEvent(QKeyEvent * event)
{
    if (!m_navigation)
        return;

    m_navigation->keyReleaseEvent(event);
}

void Canvas::mouseMoveEvent(QMouseEvent * event)
{
    if (!m_navigation)
        return;

    m_context->makeCurrent(this);
    m_navigation->mouseMoveEvent(event);

    emit mouseUpdate(event->pos());
    if (m_painter)
    {
        if (NavigationMath::validDepth(m_painter->depthAt(event->pos())))
            emit objUpdate(m_painter->objAt(event->pos()));
        else
            emit objUpdate(QVector3D());
    }
    m_context->doneCurrent();
}

void Canvas::mousePressEvent(QMouseEvent * event)
{
    if (!m_navigation)
        return;

    m_context->makeCurrent(this);
    m_navigation->mousePressEvent(event);
    m_context->doneCurrent();
}

void Canvas::mouseReleaseEvent(QMouseEvent * event)
{
    if (!m_navigation)
        return;

    m_context->makeCurrent(this);
    m_navigation->mouseReleaseEvent(event);
    m_context->doneCurrent();
}

void Canvas::mouseDoubleClickEvent(QMouseEvent * event)
{
    if (!m_navigation)
        return;

    m_context->makeCurrent(this);
    m_navigation->mouseDoubleClickEvent(event);
    m_context->doneCurrent();
}

void Canvas::wheelEvent(QWheelEvent * event)
{
    if (!m_navigation)
        return;

    m_context->makeCurrent(this);
    m_navigation->wheelEvent(event);
    m_context->doneCurrent();
}
<|endoftext|>


<commit_before>/*
 * Illarionserver - server for the game Illarion
 * Copyright 2011 Illarion e.V.
 *
 * This file is part of Illarionserver.
 *
 * Illarionserver  is  free  software:  you can redistribute it and/or modify it
 * under the terms of the  GNU Affero General Public License as published by the Free
 * Software Foundation, either version 3 of the License, or (at your option) any
 * later version.
 *
 * Illarionserver 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 Affero General Public License for more
 * details.
 *
 * You should have received a copy of the GNU Affero General Public License along with
 * Illarionserver. If not, see <http://www.gnu.org/licenses/>.
 */

#ifndef _CONNECTION_HPP_
#define _CONNECTION_HPP_

#include <memory>
#include <string>
#include <pqxx/connection.hxx>
#include <pqxx/transaction.hxx>

namespace Database {
class Connection;

using PConnection = std::shared_ptr<Connection>;

class Connection {
private:
    /* The libpgxx representation of the connection to the database. */
    std::unique_ptr<pqxx::connection> internalConnection = nullptr;
    std::unique_ptr<pqxx::transaction_base> transaction = nullptr;

public:
    explicit Connection(const std::string &connectionString);
    void beginTransaction(void);
    auto query(const std::string &query) -> pqxx::result;
    void commitTransaction(void);
    void rollbackTransaction(void);

    template<typename T> inline auto quote(const T &t) const -> std::string {
        return internalConnection->quote(t);
    }

    inline auto transactionActive() const -> bool {
        return bool(transaction);
    }

private:
    Connection(const Connection &org) = delete;
    auto operator=(const Connection &org) -> Connection & = delete;
};

}

#endif // _CONNECTION_HPP_
<commit_msg>Remove redundant void argument<commit_after>/*
 * Illarionserver - server for the game Illarion
 * Copyright 2011 Illarion e.V.
 *
 * This file is part of Illarionserver.
 *
 * Illarionserver  is  free  software:  you can redistribute it and/or modify it
 * under the terms of the  GNU Affero General Public License as published by the Free
 * Software Foundation, either version 3 of the License, or (at your option) any
 * later version.
 *
 * Illarionserver 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 Affero General Public License for more
 * details.
 *
 * You should have received a copy of the GNU Affero General Public License along with
 * Illarionserver. If not, see <http://www.gnu.org/licenses/>.
 */

#ifndef _CONNECTION_HPP_
#define _CONNECTION_HPP_

#include <memory>
#include <string>
#include <pqxx/connection.hxx>
#include <pqxx/transaction.hxx>

namespace Database {
class Connection;

using PConnection = std::shared_ptr<Connection>;

class Connection {
private:
    /* The libpgxx representation of the connection to the database. */
    std::unique_ptr<pqxx::connection> internalConnection = nullptr;
    std::unique_ptr<pqxx::transaction_base> transaction = nullptr;

public:
    explicit Connection(const std::string &connectionString);
    void beginTransaction();
    auto query(const std::string &query) -> pqxx::result;
    void commitTransaction();
    void rollbackTransaction();

    template<typename T> inline auto quote(const T &t) const -> std::string {
        return internalConnection->quote(t);
    }

    inline auto transactionActive() const -> bool {
        return bool(transaction);
    }

private:
    Connection(const Connection &org) = delete;
    auto operator=(const Connection &org) -> Connection & = delete;
};

}

#endif // _CONNECTION_HPP_
<|endoftext|>